import serial
import time
import re

class GCodeSender:
    def __init__(self, port, baudrate=115200, timeout=20):
        self.ser = serial.Serial(port, baudrate, timeout=timeout)
        self.ready = False
        # time.sleep(2)  # 等待串口初始化
        
    def wait_for_ok(self, max_retries=15):
        """等待接收OK响应"""
        retries = 0
        while retries < max_retries:
            if self.ser.in_waiting > 0:
                try:
                    response = self.ser.readline().decode().strip()
                    print(f"收到: {response}")
                    
                    # 检查是否包含ok（不区分大小写）
                    if re.search(r'ok', response, re.IGNORECASE):
                        return True
                except Exception as e:
                    print(f"发生错误: {e}")  
                    continue
            time.sleep(1)
            retries += 1
            
        print("错误: 未收到OK响应")
        return False
        
    def send_command(self, command):
        """发送单条命令并等待OK响应"""
        # 确保命令以换行符结束
        
        command += '\r\n'
            
        print(f"发送: {command.strip()}")
        self.ser.write(command.encode())
        
        return self.wait_for_ok()
        
    def send_gcode_script(self, gcode_script):
        """发送多行G代码脚本"""
        # 分割脚本为单独的行
        commands = [line.strip() for line in gcode_script.split('\n') if line.strip()]
        
        # 过滤空行和注释
        commands = [cmd for cmd in commands if cmd and not cmd.startswith(';')]
        
        # 逐条发送命令
        for i, cmd in enumerate(commands):
            print(f"进度: {i+1}/{len(commands)}")
            if not self.send_command(cmd):
                print(f"错误: 命令 '{cmd}' 执行失败")
                return False
                
        return True
       

            
    def close(self):
        """关闭串口连接"""
        self.ser.close()

# 使用示例
if __name__ == "__main__":
    # G代码脚本
    gcode_script = """
    G1 X-50 Y100 Z50 F50
    G1 X50 Y100 Z50 F50
    G1 X50 Y180 Z50 F50
    G1 X-50 Y180 Z50 F50
    G1 X-50 Y100 Z50 F50
    """
    
    # 创建发送器实例
    # 请将 'COM3' 替换为您的实际串口号
    sender = GCodeSender('COM17', 115200)
    
    try:
        # 发送G代码脚本
        success = sender.send_gcode_script(gcode_script)
        if success:
            print("所有命令执行成功!")
        else:
            print("部分命令执行失败!")
            
    except Exception as e:
        print(f"发生错误: {e}")
        
    finally:
        # 关闭连接
        sender.close()